package wscom

import (
	"encoding/json"
	"dhfshop/models/im"
	"github.com/astaxie/beego"
)

type receiveSvr struct {
	reqDao chan *im.RequestDao
}

var ReceiveSvr *receiveSvr

func NewReceiveSvr() *receiveSvr {
	return &receiveSvr{
		reqDao: make(chan *im.RequestDao, 1000), //消息中间件中最多1000条数据同时处理
	}
}

func (r *receiveSvr) Run() {
	for {
		select {
		case req := <-r.reqDao:
			r.handle(req)
		}
	}
}

/**
 * 获取消息处理器
 * websocket
 */
func (r *receiveSvr) handle(req *im.RequestDao) (err error) {
	token := "phone_" + req.UserId
	if c, err := ConnectHub.GetConnectSvr(token); err == nil {
		if message, err := json.Marshal(req); err == nil {
			if err = c.sendText(message); err != nil {
			    beego.Emergency(err.Error())
			}
		}
	}
	token = "pc_" + req.UserId
	if c, err := ConnectHub.GetConnectSvr(token); err == nil {
		if message, err := json.Marshal(req); err == nil {
			if err = c.sendText(message); err != nil {
			    beego.Emergency(err.Error())
			}
		}
	}
	return nil
}
